<template>
  <!-- svg:图标外层容器节点,内部需要与use标签结合使用 -->
  <svg v-if="obj.type === 'svg'" class="svg-icon" :style="{ width: handleWidth, height: handleHeight }" aria-hidden="true">
    <!-- xlink:href执行用哪一个图标,属性值务必#icon-图标名字 -->
    <!-- use标签fill属性可以设置图标的颜色 -->
    <use :xlink:href="prefix + name"></use>
  </svg>
  <el-icon v-bind="$attrs" v-else><component :is="name"></component></el-icon>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useDiscMinSvg } from '@/hooks/index'

defineOptions({
  name: 'SvgIcon',
})
//接受父组件传递过来的参数
let props = defineProps({
  //xlink:href属性值前缀
  prefix: {
    type: String,
    default: '#icon-',
  },
  //提供使用的图标名字
  name: {
    type: String,
    required: true,
  },
  //接受父组件传递过来的图标的宽度
  width: {
    type: [String, Number],
  },
  //接受父组件传递过来的图标的高度
  height: {
    type: [String, Number],
  },
  // 同时设置宽高
  size: {
    type: [String, Number],
    default: '16px',
  },
})

const handleWidth = computed((): string => {
  let width = typeof props.size === 'number' ? props.size + 'px' : props.size
  if (props.width) width = typeof props.width === 'number' ? props.width + 'px' : props.width
  return width
})
const handleHeight = computed((): string => {
  let height = typeof props.size === 'number' ? props.size + 'px' : props.size
  if (props.height) height = typeof props.height === 'number' ? props.height + 'px' : props.height
  return height
})
const obj = computed(() => useDiscMinSvg(props.name))
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  overflow: hidden;
  fill: currentColor;
}
</style>
